from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
import numpy as np

x_data = np.array([[1, 2, 1, 1],
                   [2, 1, 3, 2],
                   [3, 1, 3, 4],
                   [4, 1, 5, 5],
                   [1, 7, 5, 5],
                   [1, 2, 5, 6],
                   [1, 6, 6, 6],
                   [1, 7, 7, 7]],
                  dtype=np.float32)
#多分类,y需要独热编码
y_data = np.array([[0, 0, 1],
                   [0, 0, 1],
                   [0, 0, 1],
                   [0, 1, 0],
                   [0, 1, 0],
                   [0, 1, 0],
                   [1, 0, 0],
                   [1, 0, 0]],
                  dtype=np.float32)
#类别个数
nb_classes = 3
#构建模型序列:dense层3个单元,输入维度=4,激活函数softmax(多分类)
model = Sequential()
model.add(Dense(3, input_shape=(4,)))
model.add(Activation('softmax'))
#打印模型结构
model.summary()
#配置模型:categorical_crossentropy多分类交叉熵；optimizer=sgd,评估指标metrics='accuracy'
model.compile(loss='categorical_crossentropy',
              optimizer='sgd',
              metrics=['accuracy'])
#训练模型：返回训练过程中的历史数据history
history = model.fit(x_data, y_data, epochs=1000)
#预测模型的类别
print(model.predict_classes(np.array([[1, 2, 1, 1]])))
print(model.predict_classes(np.array([[1, 2, 5, 6]])))
